/**
    @author: ASUS
    @date: 2021/2/21
    @Describe:  系统状态监控
**/
package monitor

import (
	"encoding/json"
	"io"
	k "logprocess/global/kernel"
	"net/http"
	"time"
)

var TypeMonitorChan = make(chan int, 200)

type SystemInfo struct {
	HandleLine   int     `json:"handleLine"`   //总处理日志行数
	Tps          float64 `json:"tps"`          //系统吞吐量
	ReadChanLen  int     `json:"readChanLen"`  //read channel 长度
	WriteChanLen int     `json:"writeChanLen"` //write channel 长度
	RunTime      string  `json:"runTime"`      //运行总行数
	ErrNum       int     `json:"errNum"`       //错误数
}

type Monitor struct {
	StartTime time.Time
	Data      SystemInfo
	tpsSli    []int
}

func (m *Monitor) Start(l *k.LogProcess) {

	go func() {
		for v := range TypeMonitorChan {
			switch v {
			case k.TypeErrNum:
				m.Data.ErrNum += 1
			case k.TypeHandleLine:
				m.Data.HandleLine += 1
			}
		}
	}()

	ticker := time.NewTicker(time.Second * 5) //定时器

	go func() {
		for {
			<-ticker.C
			m.tpsSli = append(m.tpsSli, m.Data.HandleLine)
			if len(m.tpsSli) > 2 {
				m.tpsSli = m.tpsSli[1:]
			}
		}
	}()

	http.HandleFunc("/monitor", func(writer http.ResponseWriter, request *http.Request) {
		m.Data.RunTime = time.Now().Sub(m.StartTime).String()
		m.Data.ReadChanLen = len(l.Rc)
		m.Data.WriteChanLen = len(l.Wc)

		if len(m.tpsSli) >= 2 {
			m.Data.Tps = float64(m.tpsSli[1]-m.tpsSli[0]) / 5
		}

		marshalIndent, _ := json.MarshalIndent(m.Data, "", "\t")
		io.WriteString(writer, string(marshalIndent))
	})
	http.ListenAndServe(":9093", nil) //监听阻塞
}
